import os
import shutil
import sys
import tkinter as tk
from os import path
from tkinter import filedialog
import win32con
import win32api
from PyQt5.QtWidgets import QApplication, QMainWindow
from mainui import Ui_Dialog
import time


# 获取所有需要查询的文件名，txt文件一行一个，去掉\n
def get_codes(filepath):
    readfile = open(filepath, 'r', encoding='utf-8')
    sfc = readfile.readlines()
    real_codes = []
    for line in sfc:
        if line != "\n":
            real_codes.append(line.strip('\n'))
    return real_codes


# 查询文件总数,可以查询多级目录
def count_dir(dir_path):
    if not os.path.isdir(dir_path):
        print('Error: "', dir_path, '" is not a directory or does not exist.')
        return
    else:
        global x
    try:
        for lists in os.listdir(dir_path):
            sub_path = os.path.join(dir_path, lists)
            if os.path.isdir(sub_path):
                count_dir(sub_path)
            else:
                x += 1
    except:
        pass


class MyMainForm(QMainWindow, Ui_Dialog):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.select_file)
        self.pushButton_2.clicked.connect(self.select_path)
        self.pushButton_3.clicked.connect(self.select_output_path)
        self.pushButton_4.clicked.connect(
            lambda: self.search(self.lineEdit.text(), self.lineEdit_2.text(), self.lineEdit_3.text())
        )

    def select_path(self):
        root = tk.Tk()
        root.withdraw()
        dir_path = filedialog.askdirectory()  # 获得选择好的文件夹
        self.lineEdit_2.setText(dir_path)

    def select_output_path(self):
        root = tk.Tk()
        root.withdraw()
        dir_path = filedialog.askdirectory()  # 获得选择好的文件夹
        self.lineEdit_3.setText(dir_path)

    def select_file(self):
        root = tk.Tk()
        root.withdraw()
        filepath = filedialog.askopenfilename()  # 获得选择好的文件
        self.lineEdit.setText(filepath)

    # 开始查询主函数
    def search(self, filepath, file_dir, output_dir):
        if filepath and file_dir and output_dir:
            codes = get_codes(filepath)
            count_dir(file_dir)
            count = 0
            # 遍历查询文件夹
            for dir_path, dir_names, filenames in os.walk(file_dir):
                for f in filenames:
                    count += 1
                    self.progressBar.setValue(int((count / x) * 100))
                    self.label_5.setText('%s/%s' % (count, x))
                    QApplication.processEvents()
                    # 遍历需要查询的文件名数组
                    for c in codes:
                        if c in f:
                            shutil.copy(path.join(dir_path, f), path.join(output_dir, f))
            win32api.MessageBox(0, "搜索完成，请在%s查看结果。" % output_dir, "完成", win32con.MB_OK)
        else:
            win32api.MessageBox(0, "请选择所有选项", "错误", win32con.MB_OK)


if __name__ == '__main__':
    # x用来记录文件总数，可以全局使用
    x = 0
    # 固定的，PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表，确保程序可以双击运行
    app = QApplication(sys.argv)
    # 初始化
    myWin = MyMainForm()
    # myWin.lineEdit.setText('D:/CCD/极组条码.txt')
    # myWin.lineEdit_2.setText('D:/CCD')
    # myWin.lineEdit_3.setText('D:/CCD_result')
    # 将窗口控件显示在屏幕上
    myWin.show()
    # 程序运行，sys.exit方法确保程序完整退出。
    sys.exit(app.exec_())
    # search(filepath, file_dir, output_dir)
